#include "widget.h"
#include "ui_widget.h"

#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

/*
 * daysTo函数官方文档中明确指出此函数的功能是有部分问题的,第一天夜晚到第二天凌晨也会计算一天
 * 例如,从23:55到第二天0:05之间的10分钟差算作一天。
 * qint64 QDateTime::daysTo(const QDateTime &other) const
 * Returns the number of days from this datetime to the other datetime.
 * The number of days is counted as the number of times midnight is reached between this datetime to the other datetime.
 * This means that a 10 minute difference from 23:55 to 0:05 the next day counts as one day.
*/

void Widget::on_pushButton_clicked()
{
    // 先获取到两个输入框之间的时间
    QDateTime timeOld = ui->dateTimeEdit->dateTime();
    QDateTime timeNew = ui->dateTimeEdit_2->dateTime();
    qDebug() << "timeOld: " << timeOld;
    qDebug() << "timeNew: " << timeNew;
    // 计算日期的差值
    // qint64 days = timeOld.daysTo(timeNew); // 有部分问题的函数
    qint64 seconds = timeOld.secsTo(timeNew);
    // 秒数换算成小时和天数
    qint64 hours = (seconds / 3600) % 24;
    qint64 days = (seconds / 3600) / 24; // 手动计算天数
    qDebug() << "days: " << days;
    qDebug() << "hours: " << hours;
    qDebug() << "seconds: " << seconds;
    // 把计算结果放到label中
    ui->label->setText(QString("爱你已经持续了: ") +
                       QString::number(days) + QString("天零") +
                       QString::number(hours) + QString("小时"));
}

